package com.doradance.common.web;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Keep;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.cncn.youmengsharelib.ShareData;
import com.cncn.youmengsharelib.ShareHelper;
import com.cncn.youmengsharelib.ShareListener;
import com.cncn.youmengsharelib.SharePlatform;
import com.cncn.youmengsharelib.ui.SharePlatformsFragment;
import com.doradance.account.AccountManager;
import com.doradance.account.ui.LoginActivity;
import com.doradance.app.activity.ActivityDetailActivity;
import com.doradance.app.mine.FeedBackActivity;
import com.doradance.common.http.TokenInfo;
import com.doradance.common.pay.AliPayInfo;
import com.doradance.common.pay.AlipayHandler;
import com.doradance.common.pay.PayHelper;
import com.doradance.common.pay.PayReceiver;
import com.doradance.common.pay.PayReceiverFail;
import com.doradance.common.pay.PayResultCallback;
import com.doradance.common.pay.WechatPayEntity;
import com.doradance.entity.FileUtils;
import com.doradance.wxapi.WXPayEntryActivity;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.framework.picture.clipimage.PhotoActionHelper;
import com.pachong.android.framework.picture.picker.utils.FileManager;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.AppUtil;
import com.pachong.android.frameworkbase.utils.BitmapUtil;
import com.pachong.android.frameworkbase.utils.NetUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.app.Activity.RESULT_OK;
import static com.cncn.youmengsharelib.SharePlatform.QQ;
import static com.cncn.youmengsharelib.SharePlatform.WECHAT;
import static com.cncn.youmengsharelib.SharePlatform.WECHATMOMENTS;
import static com.pachong.android.framework.picture.browser.constant.Constant.REQUEST_CODE;
import static com.pachong.android.framework.picture.picker.Constants.Constants.IntentExtra.INTENT_SELECTED_PICTURE;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/7/28
 * 移动端接口的实现类
 */
public class MobileFunImpl implements MobileImpable {

    public static final String TAG = MobileFunImpl.class.getSimpleName();

    private CommonWebviewFragment mFragment;
    private IWXAPI msgApi;
    private PayTask alipay;
    public static PayReceiver payReceiver;
    private PayReceiverFail payReceiverFail;
    public static final int TAKE_PHOTO_REQUEST = 449;
    public static final int SELECT_ALBUM_REQUEST = 540;
    public static final int REQUEST_KEY = 585;

    public GetMediaAndUploadFragment getMediaAndUploadFragment;

    private String mFilename = "/" + System.currentTimeMillis() + ".png";
    private String mFilePath = null;
    String payResultUrl = "javascript:onPaySuccess(''," + "%1$d)";//填写支付结果 0成功，1失败
    public static Uri mImageUri;

    public MobileFunImpl(CommonWebviewFragment fragment) {
        mFragment = fragment;
        initPay();
        getToken();
    }


    private void initPay() {
        msgApi = WXAPIFactory.createWXAPI(getContext(), null);
        //将该app注册到微信
        String wetharAppid = WXPayEntryActivity.WETHAR_APPID;
        msgApi.registerApp(wetharAppid);
        alipay = new PayTask(mFragment.getActivity());
        //支付成功的回调
        payReceiver= new PayReceiver(new PayResultCallback() {
            @Override
            public void onSuccess() {
                mFragment.getWebview().loadUrl("javascript:onPaySuccess(0)");
            }
            @Override
            public void onFail() {
                mFragment.getWebview().loadUrl("javascript:onPaySuccess(1)");
            }
        });
        getContext().registerReceiver(payReceiver, new IntentFilter(WXPayEntryActivity.WECHAR_PAY));

        //支付失败的回调
        payReceiverFail= new PayReceiverFail(new PayResultCallback() {
                @Override
                public void onSuccess() {
                    mFragment.getWebview().loadUrl("javascript:onPaySuccess(1)");
                }
                @Override
                public void onFail() {

                    mFragment.getWebview().loadUrl("javascript:onPaySuccess(0)");
                }
            });
        getContext().registerReceiver(payReceiverFail, new IntentFilter(WXPayEntryActivity.WECHAR_PAY_FAIL));

    }

    private Context getContext() {
        return mFragment.getContext();
    }

    @Keep
    @JavascriptInterface
    @Override
    public String getToken() {
        String token = null;
        if (AccountManager.isTokenValid()) {
            TokenInfo tokenInfo = AccountManager.getTokenInfo();
            token = tokenInfo.toString();
            Log.e("token12112", token);
//            token = GsonUtils.toJson(tokenInfo);
        }
            return token;
    }

    @Keep
    @JavascriptInterface
    @Override
    public void startFeedBack(){
        FeedBackActivity.start(getContext());
        }

    @Keep
    @JavascriptInterface
    @Override
    public void makePhoneCall(String phoneNumber){
        try {
            JSONObject jsonObject = new JSONObject(phoneNumber);
            String phoneNumber1 = (String) jsonObject.get("phoneNumber");
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" +phoneNumber1);
            intent.setData(data);
            mFragment.startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Keep
    @JavascriptInterface
    @Override
    public void login() {
        Log.d("kyluzoi", "web use login");
    }


    //关闭活动
    @Keep
    @JavascriptInterface
    @Override
    public void closeActivity() {
    }
    @Keep
    @JavascriptInterface
    @Override
    public void backActivity(){
        ActivityDetailActivity a = new ActivityDetailActivity();
        a.ActivityDetailActivity.finish();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void goCommunity() {
//        Intent intent = new Intent();
//        intent.setClass(getContext(), SquareActivity.class);
    }


    //上传图片   单图：0     多图：1
    @Keep
    @JavascriptInterface
    @Override
    public void goUploadImage(int type){
        Log.e(TAG, "goUploadImage: ");
//        getMediaAndUploadFragment.getAudio();
    }

    //上传视频
    @Keep
    @JavascriptInterface
    @Override
    public void goUploadVedio(){
        Log.e(TAG, "goUploadVedio: ");
        getMediaAndUploadFragment.getVedio();
    }

    //上传音频
    @Keep
    @JavascriptInterface
    @Override
    public void goUploadAudio(){
        Log.e(TAG, "goUploadAudio: ");
        getMediaAndUploadFragment.getAudio();
    }


    @Keep
    @JavascriptInterface
    @Override
    public void  getFilePath(){

    }


    @Keep
    @JavascriptInterface
    @Override
    public void uploadImage(String tag) {
        Log.d("kyluzoi", "web use uploadimage");
        /*PhotoAlertFragment photoAlertFragment = new PhotoAlertFragment();
        photoAlertFragment.show(getActivity().getFragmentManager(), "tag");
        photoAlertFragment.setOnCitySelectedListener(this);
        mSynTag = tag;*/
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showToast(String url) {
//        return mConnectable.callback();
    }

    //扫二维码
    @Keep
    @JavascriptInterface
    @Override
    public void scanQrCode() {
        Intent intent = new Intent(getContext(), CaptureActivity.class);
        mFragment.startActivityForResult(intent, REQUEST_CODE);
    }
    @Keep
    @JavascriptInterface
    @Override
    public void share(String title, String content, String imgUrl, String targetUrl) {
        Log.e("kyluzoi", "web use share");
        SharePlatformsFragment fragment = SharePlatformsFragment.newInstance(title, content, imgUrl, targetUrl);
            fragment.setShareListener(new ShareListener() {
                @Override
                public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                    Toast.makeText(getContext(), "分享成功", Toast.LENGTH_SHORT).show();
                }
                @Override
                public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                    Toast.makeText(getContext(), "分享失败", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                    Toast.makeText(getContext(), "取消分享", Toast.LENGTH_SHORT).show();
                }
            });
            fragment.show(mFragment.getFragmentManager(), "");



//        ShareHelper.share(getActivity(), MySharePlatformActivity.class, shareInfo, new MyShareListener());
    }

//活动报名的分享
    @Keep
    @JavascriptInterface
    @Override
    public void shareWithTitle(String title, String content, String imgUrl, String targetUrl,int type) {
       if(type==0){
           shareType(title,content, imgUrl, targetUrl,WECHAT);
       }else if(type==1){
           shareType(title,content, imgUrl, targetUrl,WECHATMOMENTS);
       }else{
           shareType(title,content, imgUrl, targetUrl,QQ);
       }
     }

    private void shareType(String title, String content, String imgUrl, String targetUrl, SharePlatform pf) {
        ShareData shareInfo = new ShareData(imgUrl, title, content, targetUrl);
        ShareHelper.share(mFragment.getActivity(), pf, shareInfo, new ShareListener() {
            @Override
            public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                Toast.makeText(getContext(), "分享成功", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                Toast.makeText(getContext(), "分享失败", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                Toast.makeText(getContext(), "取消分享", Toast.LENGTH_SHORT).show();
            }
        });

    }


    @Keep
    @JavascriptInterface
    @Override
    public void back() {
        mFragment.getActivity().finish();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public void hideTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public boolean netIsAvalible() {
        return NetUtil.isAvalible(mFragment.getActivity());
    }

    @Keep
    @JavascriptInterface
    @Override
    public int getVersionCode() {
        return AppUtil.getVersionCode(mFragment.getActivity());
    }

    @Keep
    @JavascriptInterface
    @Override
    public void tocleanCache(){

        //清除缓存
        final File cacheDir =mFragment.getActivity().getCacheDir();
        final String cacheSize = FileUtils.size(cacheDir);
        //弹出Dialog
        showCacheDialog(cacheDir, cacheSize);

//        Toast.makeText(getContext(), cacheSize, Toast.LENGTH_SHORT).show();
//        FileUtils.delFilesFromPath(cacheDir);

//

    }

    //退出登录
    @Keep
    @JavascriptInterface
    @Override
    public void logOut() {
        //弹出Dialog
        showCacheDialog();

    }

    private void showCacheDialog(final File cacheDir, final String cacheSize) {
        if ("0B".equals(cacheSize)) {
            final AlertDialogFragment nullCacheDialogFrag = new AlertDialogFragment();
            nullCacheDialogFrag.setMessage("无缓存")
                    .setPositiveButton("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            nullCacheDialogFrag.dismiss();
                        }
                    }).show(mFragment.getFragmentManager());
        }else{
            final AlertDialogFragment cleanDialogFrag = new AlertDialogFragment();
            cleanDialogFrag.setMessage("确认清除" + cacheSize + "缓存?")
                    .setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            cleanDialogFrag.dismiss();
                        }
                    })
                    .setPositiveButton("确定", new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            FileUtils.delFilesFromPath(cacheDir);
                            cleanDialogFrag.dismiss();
                            Toast.makeText(getContext(), "已清除" + cacheSize + "缓存!", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .show(mFragment.getFragmentManager());
        }

    }
                 private void showCacheDialog() {
                     final AlertDialogFragment dialogOutFragment = new AlertDialogFragment();
                     dialogOutFragment.setMessage("是否确定退出？").setNegativeButton("取消",
                     new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             dialogOutFragment.dismiss();
                         }
                     })
                     .setPositiveButton("确定", new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             AccountManager.getTokenInfo().clear();
                             dialogOutFragment.dismiss();
                             //避免返回到退出的界面
                             mFragment.getActivity().finish();
                             LoginActivity.start(mFragment.getContext());
                         }
                     })
                    .show(mFragment.getFragmentManager());

                 }






    /**
     * 支付 paytype : 0表示支付宝，1表示微信支付
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public void pay(int payType, String orderNum) {
        switch (payType) {
            case 0:
                getAlipayInfo(orderNum);
                break;
            case 1:
//                EasyToast.showToast(mFragment.getContext(),"微信支付暂未开放");
                boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
                        && msgApi.isWXAppSupportAPI(); // 判断微信是否安装
                if (!sIsWXAppInstalledAndSupported) {
                    Toast.makeText(getContext(), "未安装微信", Toast.LENGTH_SHORT).show();
                } else {
                    getWechatPayInfo(orderNum);
                }
                break;

            default:
                break;
        }


    }
    /**
     * 获取微信支付订单详情
     *
     * @param orderNo
     */

    private void getWechatPayInfo(String orderNo) {
        PayHelper.wechatPay(getContext(), orderNo, new DataRequestListener<WechatPayEntity>(WechatPayEntity.class) {

            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(WechatPayEntity o) {
                onStartWechatPay(o);
                super.onSuccess(o);
            }
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });


    }

    /**
     * 调用微信支付
     *
     * @param wechatPayEntity
     */
    private void onStartWechatPay(WechatPayEntity wechatPayEntity) {
        PayReq request = new PayReq();
        //微信分配的公众账号ID
        request.appId = wechatPayEntity.getAppid();
        //微信支付分配的商户号
        request.partnerId = wechatPayEntity.getPartnerid();
        //微信返回的支付交易会话ID
        request.prepayId = wechatPayEntity.getPrepayid();
        //暂填写固定值Sign=WXPay
        request.packageValue = wechatPayEntity.getPackageX();
        //随机字符串，不长于32位。推荐随机数生成算法
        request.nonceStr = wechatPayEntity.getNoncestr();
        //时间戳，请见接口规则-参数规定
        request.timeStamp = wechatPayEntity.getTimestamp();
        //签名，详见签名生成算法
        request.sign = wechatPayEntity.getSign();
        msgApi.sendReq(request);


    }

    /**
     * 获取支付宝支付订单详情
     *
     * @param orderNO
     */
    private void getAlipayInfo(String orderNO) {

        PayHelper.aliPay(getContext(), orderNO, new DataRequestListener<AliPayInfo>(AliPayInfo.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(AliPayInfo o) {
                startAliPay(o);
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });

    }

    /**
     * 调用阿里支付
     */
    private AlipayHandler alipayHanlder = new AlipayHandler(new PayResultCallback(){

        @Override
        public void onSuccess() {
            mFragment.getWebview().loadUrl("javascript:onPaySuccess(0)");
        }

        @Override
        public void onFail() {
            mFragment.getWebview().loadUrl("javascript:onPaySuccess(1)");
        }
    });//启动阿里支付回调的handle


    private void startAliPay(final AliPayInfo info) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                // 调用支付接口，获取支付结果
                String result = alipay.pay(info.getOrderString());
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                alipayHanlder.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //上传头像返回结果
        if (resultCode == RESULT_OK) {
            if (requestCode == TAKE_PHOTO_REQUEST) {
                clipImage(mImageUri.getPath().toString(), mFilePath + mFilename);
            } else if (requestCode == SELECT_ALBUM_REQUEST) {
                String mHeadUrl = data.getExtras().getStringArrayList(INTENT_SELECTED_PICTURE).get(0);
                clipImage(mHeadUrl, mFilePath + mFilename);
            } else if (requestCode == REQUEST_KEY) {
                //图片压缩上传 (80*80)
                setBitmapSize();
//                sendRequest(mIcAuthPhoto);
                //最后再上传
            }
        }
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Toast.makeText(getContext(), "解析结果:" + result, Toast.LENGTH_LONG).show();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getContext(), "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void setBitmapSize() {
        Bitmap userHeader = BitmapUtil.decodeBitmapFromFilePath(mFilePath + mFilename, 80, 80);
        BitmapUtil.saveBitmap(userHeader, mFilePath + mFilename, true);
    }

    private void clipImage(String url, String outputUrl) {
        int maxWidth = 0;
        int windowWidth = mFragment.getActivity().getWindow().getWindowManager().getDefaultDisplay().getWidth();
        if (windowWidth <= 480) {
            maxWidth = 100;
        }
        PhotoActionHelper.clipImage(mFragment.getActivity())
                .input(url)
                .output(outputUrl)
                .maxOutputWidth(maxWidth)
                .requestCode(REQUEST_KEY)
                .start(mFragment);
    }
    private Uri createNewPictureUri(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(FileManager.getImagePath(context) + File.separator + "IMG_" + timeStamp + ".jpg");
        return Uri.fromFile(mediaFile);
    }
}
